/**
 * 自用业务模块
 * @type {me|exports|module.exports}
 */
const sql = require('../modules/sql.js');
const Rid = require('uuid');
const SHA1 = require('crypto-js/sha1');

module.exports = [{
    method: 'POST',
    path: '/youme/task/{uuid}',
    handler: function (req, rp) {
        var uuid = req.params.uuid;
        var body = {};
        var sqlStr = "UPDATE ym_task_record SET task_image=?,task_descr=? WHERE uuid=?";
        if (uuid == "0") {
            sqlStr = "INSERT INTO ym_task_record SET ?";
            body = req.payload.data;
            body.uuid = Rid.v1();
        } else {
            body = req.payload.data;
        }
        sql.query(sqlStr, body).then(res=> {
            if (res.code == 0 && uuid == "0") {
                return rp({
                    code: 0,
                    data: uuid == "0" ? body.uuid : uuid
                })
            } else {
                return rp(res);
            }
        })
    }
}, {
    method: 'GET',
    path: '/youme/task/{uuid}/{status}',
    handler: function (req, rp) {
        var sqlStr = "SELECT T1.uuid, T1.title,T2.uuid recordId, T2.task_image image, T2.task_descr remark, T2.done_time time, T2.status FROM ym_task T1 LEFT JOIN ym_task_record T2 ON T1.uuid = T2.task_id AND T2.create_id = '1000'";
        sql.query({
            sql: sqlStr,
            typeCast: sql.nulls
        }).then(res=> {
            return rp(res);
        })
    }
}, {
    method: 'POST',
    path: '/youme/user/add',
    handler: function (req, rp) {
        var sqlStr = "INSERT INTO `youme`.`ym_user` (`uuid`, `account`, `password`,`createTime`) VALUES (?,?,?,?)";
        const {name,pass}=req.payload;
        var data = [Rid.v1(), name, pass, new Date().getTime() + ""];
        console.dir(data);
        sql.query({
            sql: sqlStr,
            typeCast: sql.nulls
        }, data).then(res=> {
            return rp(res);
        })
    }
}, {
    method: 'POST',
    path: '/youme/user/update/{uuid}',
    handler: function (req, rp) {
        sql.updates("ym_user", {uuid: req.params.uuid}, req.payload).then(res=> {
            return rp(res);
        })
    }
}, {
    method: 'POST',
    path: '/youme/login/{type}',
    handler: function (req, rp) {
        var data,
            type = req.params.type,
            sqlStr = "SELECT * FROM `youme`.`ym_user` where account=? and password=?";
        const {name,pass,openId}=req.payload;
        if (type == 1) {
            data = [name, pass];
        } else if (type == 2) {
            sqlStr = "SELECT * FROM `youme`.`ym_user` where qq_open=?";
            data = [openId];
        }
        sql.query({
            sql: sqlStr,
            typeCast: sql.nulls
        }, data).then(res=> {
            if (res.code == 0 && res.data != "success" && res.data.length > 0) {
                return rp(res);
            }
            return rp({
                code: 404,
                data: "用户不存在"
            });

        })
    }
}, {
    method: 'GET',
    path: '/youme/bind/{mid}/{yid}',
    handler: function (req, rp) {
        const {mid,yid}=req.params;
        let joinId = SHA1([mid, yid].sort().join(",")).toString();
        sql.transaction()
            .then((conn)=> {
                return conn
            }, (err)=>rp({code: "-1", data: err}))
            .then(conn=> {
                conn.beginTransaction((error)=> {
                    if (error) throw new Error(error);
                    conn.query("update ym_user set ? where uuid=?", [{
                        partner: yid,
                        join_id: joinId
                    }, mid], (error, results)=> {
                        if (error) {
                            conn.rollback(()=> {
                                throw new Error(error)
                            });
                        } else {
                            conn.query("update ym_task_record set ? where create_id=?", [{
                                partner_id: yid,
                                join_id: joinId
                            }, mid], (error, results)=> {
                                if (error) {
                                    conn.rollback(()=> {
                                        throw new Error(error)
                                    });
                                } else {
                                    conn.commit(function (err) {
                                        if (err) {
                                            conn.rollback(function () {
                                                throw new Error(error);
                                            });
                                        }
                                        return rp({code: 0});
                                    });
                                }
                            });
                        }
                    });
                })
            })
    }
}]

